package com.wss.module.main.ui.view;

import com.orhanobut.logger.Logger;
import com.wss.common.utils.PxUtils;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Path;
import ohos.agp.text.Font;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.app.Context;
import org.jetbrains.annotations.NotNull;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义View  验证码
 * Created by 吴天强 on 2017/8/29.
 */
public class VerificationCodeView extends Component implements
        Component.DrawTask,
        Component.EstimateSizeListener {

    /**
     * 控件宽度
     */
    private int mWidth;
    /**
     * 控件高度
     */
    private int mHeight;

    private int mTextSize;
    /**
     * 绘制验证码的画笔
     */
    private Paint mTextPaint;
    /**
     * 绘制干扰点画笔
     */
    private Paint mPointPaint;
    /**
     * 绘制干扰线画笔
     */
    private Paint mPathPaint;

    /**
     * 干扰点坐标集合
     */
    private List<Point> mPoints = new ArrayList<>();
//    private Random mRandom = new Random();
    private SecureRandom mRandom = new SecureRandom();

    /**
     * 绘制贝塞尔曲线的路径集合
     */
    private List<Path> mPaths = new ArrayList<>();
    private String mText;
    private int mTextCount;

    /**
     * 验证码字符串的显示宽度
     */
    private float mTextWidth;
    private OnCodeChangeListener onCodeChangeListener;

    public VerificationCodeView(Context context) {
        this(context, null);
    }

    public VerificationCodeView(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public VerificationCodeView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);

        mTextSize = attrSet.getAttr("textSize").isPresent() ?
                attrSet.getAttr("textSize").get().getDimensionValue() : PxUtils.fp2px(16);

        mTextCount = attrSet.getAttr("textCount").isPresent() ?
                attrSet.getAttr("textCount").get().getIntegerValue() : 4;
        setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                resetCode();
            }
        });
        init();
        addDrawTask(this);
        setEstimateSizeListener(this);
    }

    @Override
    public boolean onEstimateSize(int widthMeasureSpec, int heightMeasureSpec) {
        int specWidthMode = EstimateSpec.getMode(widthMeasureSpec);
        int specSize = EstimateSpec.getSize(widthMeasureSpec);

        if (specWidthMode == EstimateSpec.PRECISE) {
            mWidth = specSize;
        } else {
            if (specWidthMode == EstimateSpec.NOT_EXCEED) {
                mWidth = Math.min((int) (mTextWidth * 1.8f), specSize);
            }
        }

        //测量高度
        int specHeightMode = EstimateSpec.getMode(heightMeasureSpec);
        specSize = EstimateSpec.getSize(heightMeasureSpec);

        if (specHeightMode == EstimateSpec.PRECISE) {
            mHeight = specSize;
        } else {
            if (specHeightMode == EstimateSpec.NOT_EXCEED) {
                mHeight = Math.min((int) (mTextWidth * 16f), specSize);
            }
        }

        setEstimatedSize(EstimateSpec.getSizeWithMode(mWidth, specWidthMode),
                EstimateSpec.getSizeWithMode(mHeight, specHeightMode));

        return true;
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        initData();
        float charLength = mTextWidth / mTextCount;
        for (int i = 1; i <= mTextCount; i++) {
            int offsetDegree = mRandom.nextInt(15);
            // 这里只会产生0和1，如果是1那么正旋转正角度，否则旋转负角度
            offsetDegree = mRandom.nextInt(2) == 1 ? offsetDegree : -offsetDegree;
            canvas.save();
            canvas.rotate(offsetDegree, mWidth >> 1, mHeight >> 1);
            // 给画笔设置随机颜色
            int argb = Color.argb(255,
                    mRandom.nextInt(200) + 20,
                    mRandom.nextInt(200) + 20,
                    mRandom.nextInt(200) + 20);
            mTextPaint.setColor(new Color(argb));
            canvas.drawText(mTextPaint, String.valueOf(mText.charAt(i - 1)), (i - 1) * charLength * 1.6f + 30, mHeight * 2 / 3f);
            canvas.restore();
        }

        // 产生干扰效果1 -- 干扰点
        for (Point pointF : mPoints) {
            int argb = Color.argb(255,
                    mRandom.nextInt(200) + 20,
                    mRandom.nextInt(200) + 20,
                    mRandom.nextInt(200) + 20);
            mPointPaint.setColor(new Color(argb));
            canvas.drawPoint(pointF.getPointX(), pointF.getPointY(), mPointPaint);
        }

        // 产生干扰效果2 -- 干扰线
        for (Path path : mPaths) {
            int argb = Color.argb(255,
                    mRandom.nextInt(200) + 20,
                    mRandom.nextInt(200) + 20,
                    mRandom.nextInt(200) + 20);
            mPathPaint.setColor(new Color(argb));
            canvas.drawPath(path, mPathPaint);
        }
    }

    /**
     * 重置验证码
     */
    private void resetCode() {
        mText = getCharAndNum(mTextCount);
        invalidate();
        if (onCodeChangeListener != null) {
            onCodeChangeListener.onCodeChanged(mText);
        }
    }

    /**
     * 初始化
     */
    private void init() {

        mText = getCharAndNum(mTextCount);

        //初始化验证码画笔
        mTextPaint = new Paint();
        mTextPaint.setColor(Color.BLACK);
        mTextPaint.setStrokeWidth(3);
        mTextPaint.setTextSize(mTextSize);

        //初始化干扰点画笔
        mPointPaint = new Paint();
        mPointPaint.setStrokeWidth(6);
        // 设置断点处为圆形
        mPointPaint.setStrokeCap(Paint.StrokeCap.ROUND_CAP);

        //初始化干扰线画笔
        mPathPaint = new Paint();
        mPathPaint.setStrokeWidth(5);
        mPathPaint.setColor(Color.GRAY);
        // 设置画笔为空心
        mPathPaint.setStyle(Paint.Style.STROKE_STYLE);
        // 设置断点处为圆形
        mPathPaint.setStrokeCap(Paint.StrokeCap.ROUND_CAP);
        // 取得验证码字符串显示的宽度值
        mTextWidth = mTextPaint.measureText(mText);

    }

    /**
     * 初始化数据
     */
    private void initData() {
        mPoints.clear();
        // 生成干扰点坐标
        for (int i = 0; i < 150; i++) {
            Point pointF = new Point(mRandom.nextInt(mWidth) + 10, mRandom.nextInt(mHeight) + 10);
            mPoints.add(pointF);
        }

        mPaths.clear();
        // 生成干扰线坐标
        for (int i = 0; i < (mRandom.nextInt(10) % 3) + 1; i++) {
            Path path = new Path();
            int startX = mRandom.nextInt(mWidth / 3) + 10;
            int startY = mRandom.nextInt(mHeight / 3) + 10;
            int endX = mRandom.nextInt(mWidth / 2) + mWidth / 2 - 10;
            int endY = mRandom.nextInt(mHeight / 2) + mHeight / 2 - 10;
            path.moveTo(startX, startY);
            path.quadTo(Math.abs(endX - startX) >> 1, Math.abs(endY - startY) >> 1, endX, endY);
            mPaths.add(path);
        }

    }

    /**
     * 设置验证码字体大小
     *
     * @param textSize 字体大小 单位sp
     */
    public void setTextSize(int textSize) {
        this.mTextSize = textSize;
    }

    /**
     * 设置验证位数
     *
     * @param textCount 位数
     */
    public void setTextCount(int textCount) {
        this.mTextCount = textCount;
    }

    /**
     * 得到验证码
     *
     * @return String
     */
    public String getText() {
        return mText;
    }

    /**
     * 当验证码
     *
     * @param listener 监听
     */
    public void addOnCodeChangeListener(OnCodeChangeListener listener) {
        this.onCodeChangeListener = listener;
    }

    /**
     * 随机生成字符串和数值
     *
     * @param length length
     * @return String
     */
    @NotNull
    private String getCharAndNum(int length) {
        StringBuilder val = new StringBuilder();
//        Random random = new Random();
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < length; i++) {
            // 输出字母还是数字
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            // 字符串
            if ("char".equalsIgnoreCase(charOrNum)) {
                // 取得大写字母还是小写字母
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val.append((char) (choice + random.nextInt(26)));
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                // 数字
                val.append(random.nextInt(10));
            }
        }
        return val.toString();
    }

    /**
     * 验证码发生变化监听
     */
    public interface OnCodeChangeListener {

        /**
         * 验证码发生了变化
         *
         * @param code 验证码
         */
        void onCodeChanged(String code);
    }
}
